import axios from "axios";
import { to } from '@jzl/utils';

const { VITE_TITLE } = import.meta.env;

let config = {};
const setConfig = (cfg) => {
  config = Object.assign(config, cfg);
};

const getConfig = (key) => {
  if (typeof key === "string") {
    const arr = key.split(".");
    if (arr && arr.length) {
      let data = config;
      arr.forEach(v => {
        if (data && typeof data[v] !== "undefined") {
          data = data[v];
        } else {
          data = null;
        }
      });
      return data;
    }
  }
  return config;
};

/** 获取项目动态全局配置 */
export const initPlatformConfig = async (app) => {
  app.config.globalProperties.$config = getConfig();

  let config = {
    // Theme: VITE_THEME,
    Title: VITE_TITLE,
    // Layout: VITE_LAYOUT
  }

  /*let [ err, ret ] = await to(axios({
    method: "get",
    url: `${ VITE_PUBLIC_PATH }platform-config.json`
  }));

  if(err) {
    return;
    // return throw "请在public文件夹下添加platform-config.json配置文件";
  }

  let config = ret?.data;*/
  let $config = app.config.globalProperties.$config;
  // 自动注入系统配置
  if (app && $config && typeof config === "object") {
    $config = Object.assign($config, config);
    app.config.globalProperties.$config = $config;
    // 设置全局配置
    setConfig($config);
  }
  return $config;
};

export { getConfig, setConfig };

export default initPlatformConfig;
